package com.example.papercut.service.impl;

import com.example.papercut.entity.PapercutTemplate;
import com.example.papercut.mapper.PapercutTemplateMapper;
import com.example.papercut.service.PapercutTemplateService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional; // 事务管理
import java.util.List;

@Service
@Transactional(readOnly = true) // 默认设置所有方法为只读事务
public class PapercutTemplateServiceImpl implements PapercutTemplateService {

    private final PapercutTemplateMapper papercutTemplateMapper;

    @Autowired
    public PapercutTemplateServiceImpl(PapercutTemplateMapper papercutTemplateMapper) {
        this.papercutTemplateMapper = papercutTemplateMapper;
    }

    @Override
    public PapercutTemplate getTemplateDetails(Integer id) {
        // 业务逻辑：如果需要，可以在此添加缓存读取逻辑
        return papercutTemplateMapper.findTemplateDetailsById(id);
    }

    @Override
    public List<PapercutTemplate> searchTemplates(
            Integer categoryId, Integer themeId, Integer techniqueId, 
            Integer layoutId, Integer authorId, String keyword, String sortBy) {
        
        // 业务逻辑：对 sortBy 参数进行安全检查，防止 SQL 注入
        if (!List.of("rating", "time", "id").contains(sortBy.toLowerCase())) {
            sortBy = "id"; // 默认安全值
        }
        
        return papercutTemplateMapper.searchTemplates(
            categoryId, themeId, techniqueId, layoutId, authorId, keyword, sortBy
        );
    }

    @Override
    @Transactional // 插入操作需要写入事务
    public void createTemplate(PapercutTemplate template) {
        // 业务逻辑：数据完整性校验 (例如，检查名称、分类ID是否缺失)
        if (template.getName() == null || template.getCategory() == null || template.getCategory().getId() == null) {
            throw new IllegalArgumentException("模板名称和分类信息不能为空。");
        }
        
        // 调用 Mapper 执行插入
        papercutTemplateMapper.insertTemplate(template);
    }
}